import streamlit as st 
from bs4 import BeautifulSoup
import os

st.set_page_config("Deepin Wiki", 'assets/deepin-wiki.png', layout='centered')

def _max_width_(prcnt_width:int = 75):
    max_width_str = f"max-width: {prcnt_width}rem;"
    st.markdown(f""" 
                <style> 
                .block-container{{{max_width_str}}}
                </style>    
                """, 
                unsafe_allow_html=True,
    )

_max_width_(st.sidebar.slider('屏幕占比', 50, 100, 75))

# <template slot="contents">


# content = ''
# with open('assets/old软件包.html') as f:
#     content = f.read()

# soup = BeautifulSoup(content, "html.parser")

# st.markdown(soup.select('[slot="contents"] div')[0].decode_contents(), unsafe_allow_html=True)

import requests
import json
def search(what):
    graphql = '''
    query ($query: String!) {
        pages { 
            search(query: $query) {
                results {        
                    id
                    title
                    description
                    path
                    locale
                    __typename
                }
                suggestions
                
                totalHits
                
                __typename
            }

            __typename
        }
    }
    '''
    
    data = [
        {
            "operationName": None,
            "variables": {
                "query": f"{what}"
            },
            "extensions": {},
            "query": graphql
        }
    ]
    
    rawdata = json.dumps(data)

    return requests.post('https://wiki.deepin.org/graphql', json=data).content.decode(errors='ignore')

searching = st.sidebar.text_input('搜索文章', value='Deepin Wiki - 深度百科')

results = []
try:
    re = search(searching)
    results = json.loads(re)[0]['data']['pages']['search']['results']
except:
    pass


# Generated by https://quicktype.io

from enum import Enum
from typing import List, Any


class Locale(Enum):
    EN = "en"
    ZH = "zh"


class Typename(Enum):
    PAGE_SEARCH_RESULT = "PageSearchResult"


class Result:
    id: str
    title: str
    description: str
    path: str
    locale: Locale
  
    def __init__(self, id: str, title: str, description: str, path: str, locale: Locale) -> None:
        self.id = id
        self.title = title
        self.description = description
        self.path = path
        self.locale = locale

    def fromJson(obj):
        return Result(
            obj['id'],
            obj['title'],
            obj['description'],
            obj['path'],
            obj['locale'],
        )


for i, v in enumerate(results):
    results[i] = Result.fromJson(v)
    
# print(results[0].id)
# print(results[0].title)
# print(results[0].description)
# print(results[0].path)
# print(results[0].locale)

if title := st.sidebar.selectbox('选择文章', options=[i.title for i in results]):
    
    with st.sidebar.expander("页面优化 - 页面显示异常可用"):
        pic_w_optimiz = st.checkbox('图片宽度优化', True)
        pic_width = st.slider('图片宽度', 50, 1000, 150, 20)
        pic_h_optimiz = st.checkbox('图片高度优化')
        pic_height = st.slider('图片高度', 10, 1000, 64, 1)
        link_optimiz = st.checkbox('链接优化 - 处理链接的指向域',True)
        if os.getenv("DEBUG_DEEPIN_WIKI") == "1":
            debug_optimiz = st.checkbox('调试器 - 显示页面代码',True)
        
    def replace_all(content:str):
        # <img alt="yeah" class="emoji" height="32px" src="assets/image/raccoon/[yeah].gif" title="yeah">
        # <img alt="IMG_20231001_091111.jpg" src="https://storage.deepin.org/thread/202310010916151757_IMG_20231001_091111.jpg">
        # content = content.replace('src="https://storage.deepin.org/', 'style="max-width: 95%;" src="https://storage.deepin.org/')

        imgstyle = 'style="'
        if pic_w_optimiz:
            # content = content.replace('<img ', f'<img width={pic_width} ')
            imgstyle += f'max-width: {pic_width}px;'
        if pic_h_optimiz:
            imgstyle += f'max-height: {pic_height}px;'
            # content = content.replace('<img ', f'<img height={pic_height} ')
        imgstyle += '"'

        content = content.replace('<img ', f'<img {imgstyle} ')

        if link_optimiz:
            content = content.replace('src="/', 'src="https://wiki.deepin.org/')
            content = content.replace('href="/', f'href="https://wiki.deepin.org/')
        return content

    
    for result in results:
        if title == result.title:
            
            content = requests.get(f'https://wiki.deepin.org/{result.locale}/{result.path}').content.decode(errors='ignore')
            # content = ''
            # with open('assets/old软件包.html') as f:
            #     content = f.read()

            soup = BeautifulSoup(content, "html.parser")
            selects = soup.select('[slot="contents"] div')
            if len(selects) > 0:
                
                st.markdown(replace_all(selects[0].decode_contents()), unsafe_allow_html=True)

                if os.getenv("DEBUG_DEEPIN_WIKI") == "1":
                    if debug_optimiz:
                        st.code(replace_all(selects[0].decode_contents()))

                st.sidebar.markdown(f'<a href="https://wiki.deepin.org/{result.locale}/{result.path}">进入: {result.title}</a>', unsafe_allow_html=True)